package repository

import (
	"gorm.io/gorm/clause"
	"niu-video/app/model"
	"niu-video/pkg/db"
)

var CollectRepository = newCollectRepository()

func newCollectRepository() *collectRepository {
	return &collectRepository{}
}

type collectRepository struct {
	baseRepository
}

// 获取用户collect
func (u *collectRepository) GetUserCollect(videoId int64, userId int64) (collect model.UserCollect) {
	db.DB.Where("video_id = ?", videoId).Where("user_id = ?", userId).First(&collect)
	return
}

func (u *collectRepository) Create(userCollect *model.UserCollect) (err error) {
	err = db.DB.Create(userCollect).Error
	return err
}

func (u *collectRepository) Delete(videoId int64, userId int64) (err error) {
	db.DB.Where("video_id = ?", videoId).Where("user_id = ?", userId).Delete(&model.UserCollect{})
	return err
}

// 获取用户collect
func (u *collectRepository) GetUserCollectByPage(page int, pageSize int,
	userId int64) (collect []model.Video) {
	order := clause.OrderByColumn{
		Column: clause.Column{
			Name: "user_collect.create_time",
		},
		Desc: true,
	}
	db.DB.Debug().Table("user_collect").Select("video.*").
		Joins("LEFT JOIN video ON user_collect.video_id = video.video_id").
		Where("user_collect.user_id = ?", userId).
		Order(order).
		Offset((page-1)*pageSize).
		Limit(pageSize).
		Where("is_delete", false).
		Find(&collect)
	return
}

// CollectCountByUserId
//
//	@Description: 获取用户的收藏数量
//	@receiver v
//	@param userId
//	@return count
func (c *collectRepository) CollectCountByUserId(userId int64) (count int64) {
	db.DB.Model(&model.UserCollect{}).
		Joins("left join video on video.video_id = user_collect.video_id").
		Where("user_collect.user_id = ?", userId).
		Where("is_delete", false).
		Count(&count)
	return
}

func (c *collectRepository) CollectUserVideo(page int, pageSize int, userId int64) (videos []model.Video, err error) {
	if err = db.DB.Debug().Table("user_collect").
		Select("video.*").
		Joins("left join video on video.video_id = user_collect.video_id").
		Where("user_collect.user_id = ?", userId).
		Order(clause.OrderByColumn{
			Column: clause.Column{
				Name: "create_time",
			},
			Desc: true,
		}).
		Offset((page-1)*pageSize).
		Limit(pageSize).
		Where("is_delete", false).
		Find(&videos).Error; err != nil {
		return videos, err
	}
	return
}
